# -*- coding: utf-8 -*-
import KBEngine
from KBEDebug import * 
import ConstDef
from FUSE_FIELD import FUSE_FIELD
import IKernel
import ValChangedDef

class FUSE_FIELD_NEST(FUSE_FIELD):
	"""
	"""
	def __init__(self):
		"""
		"""
		FUSE_FIELD.__init__(self)

	def __setitem__(self, k, v):
		if k == "FUSE_FIELD_NEST_key":
			#这个是保留关键字不能使用
			assert(False)

		if FUSE_FIELD.isKeySameType(self, k) == False:
			return

		willAddVal = FUSE_FIELD()
		dataType = type(v)
		if dataType == list : # 如果是list 那么 index 就当做key  element当做value
			for i in range(len(v)):
				element = v[i]
				if IKernel.Instance().isBaseType(element) == False:
					continue
				willAddVal[i] = element
		elif dataType == dict or dataType == FUSE_FIELD:
			for vKey, vVal in v.items():
				if IKernel.Instance().isBaseType(vVal) == False:
					continue
				willAddVal[vKey] = vVal
		else:
			ERROR_MSG("FUSE_FIELD_NEST value only suport list dict FUSE_FIELD.For deeper dict nesting, add FUSE_FIELD_3rdNEST")
			# 其他类型不支持，如果还要嵌套更深的dict，添加FUSE_FIELD_3rdNEST
			assert(False)

		oldVal = self.get(k)
		changeType = ValChangedDef.DATA_NONE
		if oldVal == None:
			changeType = ValChangedDef.DATA_ADD
		elif oldVal == v:
			return
		else:
			changeType = ValChangedDef.DATA_UPDATE

		willAddVal.owner = self
		willAddVal.ownSelfKey = k
		# 这里是越过 FUSE_FIELD 直接调用dict的 __setitem__
		dict.__setitem__(self, k, willAddVal)

		if self.owner == None:
			return

		oldValsDict = {
			k	: eval(str(oldVal)),
		}
		changeValsDict = {
			k	: eval(str(willAddVal))
		}
		self.notifyChanged(changeType, oldValsDict, changeValsDict)

	def notifyChanged(self, changeType, oldValsDict, changeValsDict):
		if self.owner == None:
			return

		# 这里如果有3层嵌套的话，需要再次通知上一层
		# 然后把ownSelfName传进去
		#oldVal = {self.ownSelfKey:oldValsDict}
		#changeVal = {self.ownSelfKey:changeValsDict}

		self.owner.onValChanged(self.ownSelfKey, oldValsDict, changeValsDict)

		from logic import ModuleMgr
		handler = ModuleMgr.Instance().getModule("ContainerHandler")
		handler.syncData(self.owner, self.ownSelfKey, changeType, changeValsDict)

	def asDict(self):
		dictData = {}
		dictData["L2"] = []

		for key, val in self.items():
			dictData["L2"].append(val)

		return dictData

	def createFromDict(self, dictData):
		# dictData["L2"] 是一个 FUSE_FIELD_MAP 的 list
		for fuseField in dictData["L2"]:
			# "FUSE_FIELD_NEST_key" 是 FUSE_FIELD 的asDict 时拥有者为 FUSE_FIELD_NEST 的时候增加的一个key
			key = fuseField["FUSE_FIELD_NEST_key"]
			self[key] = fuseField
		return self

class FUSE_FIELD_NEST_PICKLER:
	def __init__(self):
		pass

	def createObjFromDict(self, dct):
		return FUSE_FIELD_NEST().createFromDict(dct)

	def getDictFromObj(self, obj):
		return obj.asDict()

	def isSameType(self, obj):
		return isinstance(obj, FUSE_FIELD_NEST)

inst = FUSE_FIELD_NEST_PICKLER()